export default {
// state表示的是数据（购物车数据）
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || []
    // cart: [
    // {
    //   id: 1,
    //   title: '商品标题',
    //   img: '图片',
    //   price: 99.99,
    //   amount: 2,
    //   desc: '商品描述信息',
    //   checked: true
    // }
    // ]
  },
  // 唯一更新state的地方
  mutations: {
    /**
       *添加商品到购物车数组
       * @param state
       * @param payload
       */
    addToCart (state, payload) {
      const has = state.cart.some(prod => prod.id === payload.id)
      if (has) {
        state.cart = state.cart.map(prod => {
          if (prod.id === payload.id) {
            prod.amount += payload.amount
          }
          return prod
        })
      } else {
        state.cart = [
          ...state.cart,
          payload
        ]
      }
    },
    // 删除购物车中指定商品
    removeCartItem (state, payload) {
      state.cart = state.cart.filter(prod => prod.id !== payload)
    },
    // 修改购物车中的数量
    changeCartTtemAmount (state, payload) {
      state.cart = state.cart.filter(prod => {
        if (prod.id === payload.id) {
          prod.amount = payload.amount
        }
        return prod
      })
    },
    // 切换选中
    toggleCartItem (state, payload) {
      state.cart = state.cart.map(prod => {
        if (prod.id === payload) {
          prod.checked = !prod.checked
        }
        return prod
      })
    },
    // 全选按钮切换
    toggleAllCheched (state, payload) {
      state.cart = state.cart.map(prod => {
        prod.checked = payload
        return prod
      })
    }

  },
  actions: {

  },
  // 相当于组建的计算属性computed
  getters: {
    //  计算购物车数量
    totalCount (state) {
      return state.cart.reduce((sum, curr) => {
        sum += curr.amount
        return sum
      }, 0)
    },
    // 修改状态
    checkedAll (state) {
      return state.cart.every(prod => prod.checked)
    },
    // 计算价格
    totalMoney (state) {
      return state.cart.reduce((sum, prop) => {
        if (prop.checked) {
          sum += prop.price * prop.amount
        }
        return sum
      }, 0) * 100
    }
  }
}
